package com.jumi.microservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jumi.microservice.common.base.dto.BasePageResponse;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.common.utils.ResultGenerator;
import com.jumi.microservice.constant.ExceptionEnum;
import com.jumi.microservice.constant.StatusEnum;
import com.jumi.microservice.domain.ArticleClass;
import com.jumi.microservice.domain.Log;
import com.jumi.microservice.domain.LogDetailVO;
import com.jumi.microservice.domain.OperateLogQuery;
import com.jumi.microservice.domain.dto.ArticleClassDTO;
import com.jumi.microservice.domain.dto.ArticleDTO;
import com.jumi.microservice.domain.vo.ArticleClassQuery;
import com.jumi.microservice.domain.vo.ArticleClassVO;
import com.jumi.microservice.domain.vo.ArticleVO;
import com.jumi.microservice.mapper.ArticleClassMapper;
import com.jumi.microservice.service.ArticleClassService;
import com.jumi.microservice.service.LogService;
import com.jumi.microservice.utils.LogObjectCopyUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.List;
import java.util.stream.Collectors;

/**
 *  文章分类管理controller组件
 */
@RestController
@Api(tags = "文章分类相关接口")
@RequestMapping("/auth/articleClass")
public class ArticleClassController {

    @Autowired
    private ArticleClassService articleClassService;
    @Autowired
    private ArticleClassMapper articleClassMapper;
    @Autowired
    private LogService logService;

    @ApiOperation(value = "新增文章类型", notes = "新增一条表数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "分类标识码", value = "acCode"),
            @ApiImplicitParam(name = "分类名称", value = "acName"),
            @ApiImplicitParam(name = "父ID", value = "acParent_id"),
            @ApiImplicitParam(name = "排序", value = "acSort"),
    })
    @PostMapping("/add")
    public ResponseResult add(@Validated @RequestBody ArticleClassVO vo, HttpServletRequest request){
        ArticleClassDTO dto = vo2Dto(vo);
        articleClassService.insert(dto,request);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "编辑文章类型", notes = "编辑一条表数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "acid"),
            @ApiImplicitParam(name = "分类标识码", value = "acCode"),
            @ApiImplicitParam(name = "分类名称", value = "acName"),
            @ApiImplicitParam(name = "排序", value = "acSort"),
    })
    @PutMapping("/update")
    public ResponseResult update(@Validated @RequestBody ArticleClassVO vo, HttpServletRequest request){
        ArticleClassDTO articleClass = articleClassService.selectById(vo.getAcid());
        articleClass.setAcName(vo.getAcName());
        articleClassService.update(articleClass,request);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "删除分类数据", notes = "删除指定ID分类表数据")
    @ApiImplicitParam(name = "id", value = "ID")
    @DeleteMapping("/delete")
    public ResponseResult delete(String id,HttpServletRequest request){
        articleClassService.delete(id,request);
        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "分页查询", notes = "获取部门表分页列表数据")
    @GetMapping("/list")
    public BasePageResponse list(
            @RequestParam(defaultValue = "0") Integer page,
            @RequestParam(defaultValue = "0") Integer size,
            ArticleClassQuery articleClassQuery){
        LambdaQueryWrapper<ArticleClass> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(StringUtils.isNotEmpty(articleClassQuery.getAcName()),ArticleClass::getAcName,articleClassQuery.getAcName());
        wrapper.eq(articleClassQuery.getStatus() != null,ArticleClass::getStatus,articleClassQuery.getStatus());
        wrapper.ge(StringUtils.isNotEmpty(articleClassQuery.getStartTimeUp()), ArticleClass::getUpdateTime, articleClassQuery.getStartTimeUp());
        wrapper.le(StringUtils.isNotEmpty(articleClassQuery.getEndTimeUp()), ArticleClass::getUpdateTime, articleClassQuery.getEndTimeUp());
        wrapper.eq(ArticleClass::getIsDel, StatusEnum.STATUS_NO.getCode());
        wrapper.orderByDesc(ArticleClass::getUpdateTime);

        IPage<ArticleClass> pageInfo = articleClassService.page(new Page<>(page, size), wrapper);
        for (ArticleClass articleClass : pageInfo.getRecords()) {
            if(articleClass.getAcParentId() > 0){
                ArticleClass articClassArray = articleClassMapper.selectById(articleClass.getAcParentId());
                String acName = articClassArray.getAcName();
                articleClass.setAcParentName(acName+"->"+articleClass.getAcName());
            }
        }

        return ResultGenerator.genSuccessResultPage(pos2Vos(pageInfo.getRecords()), pageInfo.getTotal());
    }


    @ApiOperation(value = "编辑状态", notes = "编辑指定ID分类表数据状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID"),
            @ApiImplicitParam(name = "状态，1启用，0.禁用", value = "status"),
    })
    @PutMapping("/status")
    public ResponseResult status(Long id, Integer status,HttpServletRequest request){
        articleClassService.status(id,status,request);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "查询数据", notes = "获取指定ID文章表数据")
    @ApiImplicitParam(name = "id", value = "ID")
    @GetMapping("/detail")
    public ResponseResult<ArticleClassVO> detail(Long id){
        ArticleClassDTO articleClassDTO = articleClassService.selectById(id);
        if(articleClassDTO.getAcParentId() > 0){
            ArticleClass articClassArray = articleClassMapper.selectById(articleClassDTO.getAcParentId());
            articleClassDTO.setAcParentName(articClassArray.getAcName());
        }
        return ResultGenerator.genSuccessResult(dto2Vo(articleClassDTO));
    }

    @ApiOperation(value = "模块操作日志查询", notes = "模块操作日志查询分页列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码"),
            @ApiImplicitParam(name = "size", value = "分页大小"),
    })
    @GetMapping("/listLog")
    public BasePageResponse listLog(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "0") Integer size,
            OperateLogQuery logQuery) {
        Page<Log> list = logService.listOperateLogs(logQuery);
        //处理分页
//        if(list.size()>size){
//            return ResultGenerator.genSuccessResultPage(
//                    list.stream()
//                            .skip(size * (page - 1))
//                            .limit(size).collect(Collectors.toList())
//                    ,Long.valueOf(list.size()));
//        }
        return ResultGenerator.genSuccessResultPage(LogObjectCopyUtil.convertOperateLogDoList2VoList(list.getRecords()), list.getTotal());
    }

    /**
     * 部门DO对象转换 do->vo
     *
     * @param articleClasses 部门do集合
     * @return 部门VO集合
     */
    private List<ArticleClassVO> pos2Vos(List<ArticleClass> articleClasses) {
        List<ArticleClassVO> pos = articleClasses.stream().map(p -> {
            ArticleClassVO vo = null;
            try {
                vo = p.clone(ArticleClassVO.class);
            } catch (Exception e) {
                ExceptionEnum.FAIL_CHANGE.newException();
            }
            return vo;
        }).collect(Collectors.toList());
        return pos;
    }

    /**
     * 分类VO对象转换 vo->dto
     * @param vo
     * @return
     */
    private ArticleClassDTO vo2Dto(ArticleClassVO vo) {
        ArticleClassDTO dto = null;
        try {
            dto = vo.clone(ArticleClassDTO.class);
        } catch (Exception e) {
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return dto;
    }


    /**
     * 部门对象转换 dto->vo
     *
     * @param dto 部门dto
     * @return 部门vo
     */
    private ArticleClassVO dto2Vo(ArticleClassDTO dto) {
        ArticleClassVO vo = null;
        try {
            vo = dto.clone(ArticleClassVO.class);
        } catch (Exception e) {
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return vo;
    }
}
